﻿#include "robotcontrolwidget.h"
#include <QLabel>
#include <QThread>
#include <models/robotlist.h>
#include "models/command.h"



RobotControlWidget::RobotControlWidget(QWidget *parent)
    : QWidget(parent)
{
    //setFixedSize(1440*g_xScale, 350*g_xScale);
    setStyleSheet("background-color: #2E2F31;");

    initUI();
}

RobotControlWidget::~RobotControlWidget()
{
    // 先断开所有信号连接
    if(mainSlider) {
        mainSlider->disconnect();
    }
    if(tipSlider1) {
        tipSlider1->disconnect();
    }
    if(tipSlider2) {
        tipSlider2->disconnect();
    }
    
    // 清理jointSliders
    for(auto& slider : jointSliders) {
        if(slider) {
            slider->disconnect();
            slider->deleteLater();  // 使用deleteLater而不是直接删除
        }
    }
    jointSliders.clear();
    // 清理布局中的所有部件
    if(jointWidget && jointWidget->layout()) {
        QLayout* layout = jointWidget->layout();
        while(QLayoutItem* item = layout->takeAt(0)) {
            if(QWidget* widget = item->widget()) {
                widget->disconnect();
                widget->deleteLater();
            }
            delete item;
        }
    }
}

void RobotControlWidget::initUI()
{
    mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建顶部区域
    QWidget *headerWidget = new QWidget;
    headerWidget->setFixedHeight(80*g_xScale);
    headerWidget->setStyleSheet("background-color: #2E2F31;");
    QHBoxLayout *headerLayout = new QHBoxLayout(headerWidget);
    headerLayout->setContentsMargins(15*g_xScale, 15*g_xScale, 15*g_xScale, 0);

    // 创建按钮组容器
    QWidget *buttonContainer = new QWidget;
    buttonContainer->setStyleSheet("background-color: #48494E;border-radius: 3px;");
    QHBoxLayout *buttonContainerLayout = new QHBoxLayout(buttonContainer);
    buttonContainerLayout->setContentsMargins(0, 0, 0, 0);
    buttonContainerLayout->setSpacing(0);

    // 创建主滑块相关控件
    sliderContainer = new QWidget(headerWidget);
    sliderContainer->setFixedHeight(60*g_xScale);
    sliderContainer->setStyleSheet("background-color: #48494E;border-radius: 3px;");

    createSlider(sliderContainer,mainSlider,90,"°");
    tipSliderContainer = new QWidget(headerWidget);
    tipSliderContainer->setFixedHeight(60*g_xScale);
    tipSliderContainer->setStyleSheet("background-color: #48494E;border-radius: 3px;");
    createSlider(tipSliderContainer,tipSlider1,100,"cm");
    createSlider(tipSliderContainer,tipSlider2,90,"°");

    // 添加到布局
    headerLayout->addWidget(tipSliderContainer);
    headerLayout->addStretch(1);  // 中间弹簧
    headerLayout->addWidget(sliderContainer);
    mainLayout->addWidget(headerWidget);

    jointWidget = new QWidget(this);
    jointWidget->setStyleSheet("background-color: #2E2F31;");
    mainLayout->addWidget(jointWidget, 1);
}

void RobotControlWidget::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
        connect(pCurRobot,&Robot::sportStateChanged, this, &RobotControlWidget::updateData,Qt::UniqueConnection);
}


void RobotControlWidget::setJointCount(JointType tempJointType)
{
    curJointType=tempJointType;
    //onModeChanged(currentMode);
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(!pCurRobot)
        return;
    QVector<JOINT> joints = getJointByType(tempJointType);
    //切换步进值滑块
    switch (curJointType)
    {
    case LEFT_TIP_JOINT:
    case RIGHT_TIP_JOINT:
        sliderContainer->setVisible(false);
        tipSliderContainer->setVisible(true);
        break;
    default:
        tipSliderContainer->setVisible(false);
        sliderContainer->setVisible(true);
        break;
    }
    // 安全清理现有的滑块
    for(auto& slider : jointSliders)
    {
        if(slider) {
            slider->disconnect();
            if(jointWidget && jointWidget->layout()) {
                jointWidget->layout()->removeWidget(slider);
            }
            slider->hide();
        }
    }
    // 创建新的网格布局
    QGridLayout* jointLayout = static_cast<QGridLayout*>(jointWidget->layout());
    if(!jointLayout)
    {
        jointLayout = new QGridLayout(jointWidget);
        // 设置布局从左开始排列
        jointLayout->setAlignment(Qt::AlignLeft | Qt::AlignTop);
        int nNum=21*g_xScale;
        jointLayout->setSpacing(nNum);
        jointLayout->setContentsMargins(nNum, nNum, nNum, nNum);
    }

    for (int i = 0; i < joints.size(); i++)
    {
        // 确保有两个数据可用
        JointSliderWidget *jointSlider = NULL;
        if(i< jointSliders.size())
        {
            jointSlider = jointSliders[i];
        }
        else
        {
            jointSlider = new JointSliderWidget((width()-21*g_xScale*4)/3,100*g_xScale,jointWidget);
            jointSliders.append(jointSlider);
        }
        connect(jointSlider, &JointSliderWidget::start,
                this, &RobotControlWidget::onJointSliderStart,
                Qt::UniqueConnection);
        connect(jointSlider, &JointSliderWidget::stop,
                this, &RobotControlWidget::onJointSliderStop,
                Qt::UniqueConnection);
        int row = i % 3;
        int col = i / 3;
        float fCurValue = 0.0;
        switch (curJointType){
        case LEFT_TIP_JOINT:
        {
            QVector<float> leftTip = pCurRobot->leftTip();
            if(i<leftTip.size())
            {
                if(i < 3)
                    fCurValue = leftTip[i]* 100;
                else
                    fCurValue = leftTip[i]* 180/M_PI;
            }
        }
            break;
        case RIGHT_TIP_JOINT:
        {
            QVector<float> rightTip = pCurRobot->rightTip();
            if(i<rightTip.size())
            {
                if(i < 3)
                    fCurValue = rightTip[i]* 100;
                else
                    fCurValue = rightTip[i]* 180/M_PI;
            }
        }
            break;
        case LEFT_TOOL_HAND_JOINT:
        case LEFT_TOOL_GRIPPER_JOINT:
        case LEFT_TOOL_SUCKER_JOINT:
        {
            QVector<float> fArcs = pCurRobot->leftFingerArc();
            if(i<fArcs.size())
                fCurValue = fArcs[i]/** 180/M_PI*/;
        }
            break;
        case RIGHT_TOOL_HAND_JOINT:
        case RIGHT_TOOL_GRIPPER_JOINT:
        case RIGHT_TOOL_SUCKER_JOINT:
        {
            QVector<float> fArcs = pCurRobot->rightFingerArc();
            if(i<fArcs.size())
                fCurValue = fArcs[i]/** 180/M_PI*/;
        }
            break;
        default:
            QVector<float> fArcs = pCurRobot->getJointsArc(curJointType);
            if(i<fArcs.size())
                fCurValue = fArcs[i]* 180/M_PI;
            break;
        }

        switch (curJointType) {
        case LEFT_TIP_JOINT:
        case RIGHT_TIP_JOINT:
            if(i<3) {
                jointSlider->setStep(tipSlider1->floatValue());
                connect(tipSlider1, &CustomSlider::floatValueChanged,
                        jointSlider, &JointSliderWidget::setStep,
                        Qt::UniqueConnection);
                jointSlider->init(i,joints[i].strName,"cm",-200.0f, 200.0f,fCurValue);
            }
            else if(i>=3&&i<6)
            {
                jointSlider->setStep(tipSlider2->floatValue());
                connect(tipSlider2, &CustomSlider::floatValueChanged,
                        jointSlider, &JointSliderWidget::setStep,
                        Qt::UniqueConnection);
                jointSlider->init(i,joints[i].strName,"°",-180.0f, 180.0f,fCurValue);
            }
            jointLayout->addWidget(jointSlider, row, col);
            break;
        default:
            if(mainSlider) {
                jointSlider->setStep(mainSlider->floatValue());
                connect(mainSlider, &CustomSlider::floatValueChanged,
                        jointSlider, &JointSliderWidget::setStep,
                        Qt::UniqueConnection);
            }
            jointSlider->init(i,joints[i].strName,"°",-180.0f, 180.0f,fCurValue);
            jointLayout->addWidget(jointSlider, col, row);
            break;
        }
        jointSlider->show();
    }
}

void RobotControlWidget::onJointSliderStart(int jointId, float value)
{
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        switch (curJointType){
        case LEFT_TIP_JOINT:
        case RIGHT_TIP_JOINT:
        {
            if(jointId<3)
                pCurRobot->startSetJoint(curJointType,jointId,value/100);
            else if(jointId >=3 &&jointId <6)
                pCurRobot->startSetJoint(curJointType,jointId,value*M_PI/180);
            break;
        }
            break;
        default: pCurRobot->startSetJoint(curJointType,jointId,value*M_PI/180);
            break;
        }

    }
}

void RobotControlWidget::onJointSliderStop(int jointId)
{
    Q_UNUSED(jointId);
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        pCurRobot->stopSetJoint();
    }
}

void RobotControlWidget::createSlider(QWidget* &tempSliderContainer,CustomSlider* &tempSlider,float fMax ,QString strUnit)
{
    // 创建背景容器
    QHBoxLayout *containerLayout = (QHBoxLayout *)tempSliderContainer->layout();
    if(!containerLayout)
    {
        containerLayout = new QHBoxLayout(tempSliderContainer);
        containerLayout->setSpacing(10*g_xScale);
        containerLayout->setContentsMargins(10*g_xScale, 10*g_xScale, 10*g_xScale, 10*g_xScale);
    }
    // 创建控件

    QLabel * stepLabel;
    DirectionButton * leftBtn;
    DirectionButton * rightBtn;

    leftBtn = new DirectionButton(true, sliderContainer);
    rightBtn = new DirectionButton(false, sliderContainer);
    leftBtn->setFixedSize(28*g_xScale, 28*g_xScale);
    rightBtn->setFixedSize(28*g_xScale, 28*g_xScale);

    // 设置按钮样式，使用图片背景
    leftBtn->setText("");  // 清除文本
    rightBtn->setText("");  // 清除文本
    leftBtn->setStyleSheet(
                "QPushButton {"
                "    border: none;"
                "    border-image: url(:/images/control_from/sub_btn.png);"
                "    background-color: transparent;"
                "}"
                "QPushButton:pressed {"
                "    border: none;"
                "    border-image: url(:/images/control_from/sub_pressed.png);"
                "    background-color: transparent;"
                "}"
                );
    rightBtn->setStyleSheet(
                "QPushButton {"
                "    border: none;"
                "    border-image: url(:/images/control_from/add_btn.png);"
                "    background-color: transparent;"
                "}"
                "QPushButton:pressed {"
                "    border: none;"
                "    border-image: url(:/images/control_from/add_pressed.png);"
                "    background-color: transparent;"
                "}"
                );

    // QString sliderStyle = QString("QSlider {"
    //                      "    background: transparent;"
    //                      "}"
    //                      "QSlider::groove:horizontal {"
    //                      "    background: #1F1F1F;"
    //                      "    height: %3px;"  // 背景高度15px
    //                      "    border-radius: %4px;"  // 圆角为高度的一半
    //                      "}"
    //                      "QSlider::handle:horizontal {"
    //                      "    border-image: url(:/images/control_from/slider_ico.png);"
    //                      "    width: %1px;"
    //                      "    height: %2px;"
    //                      "}"
    //                      )
    //                  .arg(int(18*g_xScale)).arg(int(40*g_xScale)).arg(int(10*g_xScale)).arg(int(8*g_xScale));


    QString labelStyle=QString("QLabel{ \
                               color: white; \
            background: transparent;}");
tempSlider = new CustomSlider(sliderContainer);

QFont font = this->font();
font.setPixelSize(16*g_xScale);
font.setFamily("微软雅黑");
stepLabel = new QLabel("30", sliderContainer);
stepLabel->setStyleSheet(labelStyle);
stepLabel->setFont(font);
//tempSlider->setStyleSheet(sliderStyle);
stepLabel->setFixedSize(65*g_xScale,28*g_xScale);
stepLabel->setAlignment(Qt::AlignCenter);

// 设置滑块尺寸
tempSlider->setFixedSize(313*g_xScale,43*g_xScale);  // 减小滑块宽度

// 设置初始值和范围
tempSlider->setFloatRange(0.0f, fMax);

// 将控件添加到背景容器的布局中
// containerLayout->addWidget(iconLabel);
containerLayout->addWidget(leftBtn);
containerLayout->addWidget(tempSlider);
containerLayout->addWidget(stepLabel);
containerLayout->addWidget(rightBtn);

// 移除弹性空间，让容器大小适应内容
containerLayout->setSizeConstraint(QLayout::SetFixedSize);

// 连接信号和槽
connect(leftBtn, &DirectionButton::stepClicked, this, [=](bool step) {
    Q_UNUSED(step);
    if(tempSlider) {
        float newValue = tempSlider->floatValue() -  0.1f;
        tempSlider->setFloatValue(newValue);
    }
});

connect(rightBtn, &DirectionButton::stepClicked, this, [=](bool step) {
    Q_UNUSED(step);
    if(tempSlider) {
        float newValue = tempSlider->floatValue() + 0.1f;
        tempSlider->setFloatValue(newValue);
    }
});

connect(tempSlider, &CustomSlider::floatValueChanged, this, [=](float value) {
    stepLabel->setText( QString::number(value, 'f', 1) + strUnit);
});
tempSlider->setFloatValue(1.0);
}


void RobotControlWidget::updateData()
{
    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        QVector<JOINT> joints = getJointByType(curJointType);
        switch (curJointType){
        case LEFT_TIP_JOINT:
        {
            QVector<float> leftTip = pCurRobot->leftTip();
            for (int i = 0; i < jointSliders.size() &&i<leftTip.size(); ++i) {
                if(i<3)
                    jointSliders[i]->setCurValue(leftTip[i]*100);  // 转换回浮点数
                else
                    jointSliders[i]->setCurValue(leftTip[i]* 180/M_PI);  // 转换回浮点数
            }
        }
            break;
        case RIGHT_TIP_JOINT:
        {
            QVector<float> rightTip = pCurRobot->rightTip();
            for (int i = 0; i < jointSliders.size() &&rightTip.size()>i; i++) {
                if(i<3)
                    jointSliders[i]->setCurValue(rightTip[i]*100);  // 转换回浮点数
                else
                    jointSliders[i]->setCurValue(rightTip[i]* 180/M_PI);  // 转换回浮点数
            }
        }
            break;
        case LEFT_TOOL_HAND_JOINT:
        case LEFT_TOOL_GRIPPER_JOINT:
        case LEFT_TOOL_SUCKER_JOINT:
        {
            QVector<float> fArcs = pCurRobot->leftFingerArc();
            for (int i = 0; i < jointSliders.size()  && i<joints.size()&& joints[i].nIndex<fArcs.size(); i++) {
                jointSliders[i]->setCurValue(fArcs[joints[i].nIndex] /** 180/M_PI*/);  // 转换回浮点数
            }
        }
            break;
        case RIGHT_TOOL_HAND_JOINT:
        case RIGHT_TOOL_GRIPPER_JOINT:
        case RIGHT_TOOL_SUCKER_JOINT:
        {
            QVector<float> fArcs = pCurRobot->rightFingerArc();
            for (int i = 0; i < jointSliders.size()  && i<joints.size()&& joints[i].nIndex<fArcs.size() ; i++) {
                jointSliders[i]->setCurValue(fArcs[joints[i].nIndex] /** 180/M_PI*/);  // 转换回浮点数
            }
        }
            break;
        default:
            QVector<float> fArcs = pCurRobot->getJointsArc(curJointType);
            for (int i = 0; i < jointSliders.size() &&fArcs.size()>i; i++) {
                jointSliders[i]->setCurValue(fArcs[i] * 180/M_PI);  // 转换回浮点数
            }
            break;
        }
    }
}
